﻿using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Schedulingclasses.Api.DTO;
using Schedulingclasses.Api.User.Command;
using Schedulingclasses.Domain;
using Schedulingclasses.ErrorCode;
using Schedulingclasses.Infrastructure;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using static Humanizer.In;

namespace Schedulingclasses.Api.User.Handler
{
    /// <summary>
    ///登录
    /// </summary>
    public class LoginHandler : IRequestHandler<LoginCommand, ApiResult<LoginDto>>
    {
        private readonly IBaseRepository<Userinfo> userinfo;
        private readonly IBaseRepository<Roleinfo> roleinfo;
        private readonly IBaseRepository<UserRoleinfo> userroleinfo;
        private readonly ILogger<LoginHandler> logger;

        public LoginHandler(IBaseRepository<Userinfo> userinfo,IBaseRepository<Roleinfo> roleinfo,IBaseRepository<UserRoleinfo> userroleinfo,ILogger<LoginHandler> logger)
        {
            this.userinfo = userinfo;
            this.roleinfo = roleinfo;
            this.userroleinfo = userroleinfo;
            this.logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<LoginDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("登录操作");
                var res = new ApiResult<LoginDto>();

                var info = await userinfo.GetValue(x => x.Username.Equals(request.Username));
                if (info == null)
                {
                    res.msg = "用户错误，或密码不正确";
                    return res;
                }

      

                if (info.Password != request.Password.GetMD5())
                {
                    res.msg = "密码不正确";
                    return res;
                }

                //通过中间表查到用户
                var userrole = await userroleinfo.GetValue(x => x.UserId.Equals(info.UserId));
                //获取角色
                var role = await roleinfo.GetValue(x => x.RoleId.Equals(userrole.RoleId));

                var model = new LoginDto()
                {
                    UserId=info.UserId,
                    Username=info.Username,
                    Password=info.Password,
                    Nickname=info.Nickname,
                    RoleId= role.RoleId,
                    RoleName=role.RoleName,
                    Token= CreateTokenString()
                };

                res.msg = "登录成功";

                res.success(model);
                return res;

                


            }
            catch (Exception ex)
            {

                logger.LogError("登录出现问题了" + ex.Message);
                throw ex;
            }
        }

        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
